package com.xuecheng.ucenter.service;

import com.xuecheng.framework.domain.ucenter.XcCompanyUser;
import com.xuecheng.framework.domain.ucenter.XcUser;
import com.xuecheng.framework.domain.ucenter.ext.XcUserExt;
import com.xuecheng.ucenter.dao.XcCompanyUserRepository;
import com.xuecheng.ucenter.dao.XcUserRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Optional;

@Service
public class XcUserService {
    @Resource
    private XcUserRepository xcUserRepository;

    @Resource
    private XcCompanyUserRepository xcCompanyUserRepository;

    /**
     * 根据用户账号,查询一个用户信息
     *
     * @param userName 用户名
     * @return {@link XcUserExt}
     */
    public XcUserExt getUserExt(String userName) {
        XcUser xcUser = this.findXcUserByUserName(userName);
        if (xcUser == null) {
            return null;
        }
        XcCompanyUser xcCompanyUser = this.findXcCompanyUserByUserId(xcUser.getId());
        String companyId = null;
        if (xcCompanyUser != null) {
            companyId = xcCompanyUser.getCompanyId();
        }
        XcUserExt xcUserExt = new XcUserExt();
        BeanUtils.copyProperties(xcUser, xcUserExt);
        xcUserExt.setCompanyId(companyId);
        return xcUserExt;
    }

    /**
     * 根据用户名查询一个用户
     *
     * @param userName 用户名
     * @return {@link XcUser}
     */
    private XcUser findXcUserByUserName(String userName) {
        Optional<XcUser> optional = xcUserRepository.findByUsername(userName);
        return optional.orElse(null);
    }

    private XcCompanyUser findXcCompanyUserByUserId(String userId) {
        return xcCompanyUserRepository.findByUserId(userId);
    }
}
